const ProductService = require("../../services/admin/ProductService")




const ProductController = {
    add: async (req, res) => {
        try {
            // console.log(req.file, req.body);
            // 产品封面获取，如果不存在则为空
            const cover = req.file ? `/productuploads/${req.file.filename}` : ""
            const { title, introduction, detail, publisher } = req.body
            await ProductService.add({ title, introduction, detail, publisher, cover, editTime: new Date() })
            res.send({
                ActionType: "OK"
            })
        } catch (error) {
            res.send({ errorMsg: "添加产品失败，产品已存在" });
        }
    },
    getAll:async (req,res) => {
        try {
            const result = await ProductService.getAll()
            res.send({
                ActionType: "OK",
                data: result
            })
        } catch (error) {
            res.send({ errorMsg: "查询产品列表失败" });
            
        }
    },
    getListByPublisher: async (req, res) => {
        try {
            const result = await ProductService.getListByPublisher({ publisher: req.params.publisher })
            res.send({
                ActionType: "OK",
                data: result
            })
        } catch (error) {
            res.send({ errorMsg: "查询产品列表失败" });

        }
    },
    deleteProduct: async (req, res) => {
        try {
            await ProductService.deleteProduct({ _id: req.params.id })
            res.send({
                ActionType: "OK"
            })
        } catch (error) {
            res.send({ errorMsg: "删除产品失败" })
        }
    },
    getProductById: async (req, res) => {
        try {
            const result = await ProductService.getProductById({ _id: req.params.id })
            res.send({
                ActionType: "OK",
                data: result
            })
        } catch (error) {
            res.send({ errorMsg: "获取产品信息失败" })
        }
    },
    update: async (req, res) => {
        try {
            // console.log(req.file, req.body);
            // 封面获取，如果不存在则为空
            const cover = req.file ? `/productuploads/${req.file.filename}` : ""
            const { _id, title, introduction, detail } = req.body
            await ProductService.update({ _id, title, introduction, detail, cover, editTime: new Date() })
            res.send({
                ActionType: "OK"
            })
        } catch (error) {
            res.send({ errorMsg: "更新新闻失败" });
        }
    }
}


module.exports = ProductController